/**
 * @desc
 * webpack打包后处理逻辑 ..
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/12/7
 **/
'use strict';


let fse = require('fs-extra');
let path = require('path');
let ossConfig = require('../../config').ossConfig;
let ossClient = require('@qianmi/x-site-common/util/oss').getOssClient(ossConfig);

module.exports = ({assetsByChunkName, envCode}) => {
    let baseDir = OssMap[envCode];
    console.log('打包后生成文件内容::', assetsByChunkName);
    let content = Object.keys(assetsByChunkName).map((key) => {
        let {jsPath, cssPath} = _extraJsCssPath(assetsByChunkName[key]);
        return `
     "${key}":{
        "jsFile":"${baseDir + jsPath}",
        "cssFile":"${baseDir + cssPath}"
       }
    `;
    });

    //上传文件到阿里云去;;
    let assetsJson = JSON.parse("{" + content.join(',') + "}");
    fse.outputFileSync(path.join(__dirname, '../../', './auto/bundle-map.js'), `//由打包自动生成文件
        module.exports=${JSON.stringify(assetsJson)};`);

    //TODO gai
    if (( envCode === 'prod' || envCode === 'gray' )) {
        console.log('上传bundle文件 到阿里云上: 执行命令,');

        (async() => {
            for (let key in assetsByChunkName) {
                let {jsPath, cssPath} = _extraJsCssPath(assetsByChunkName[key]);
                await  ossClient.putObjectAbsolute(path.join(__dirname, '../build', jsPath), `/x-site-admin/${envCode}/public/build/` + jsPath);
                if (cssPath) {
                    await  ossClient.putObjectAbsolute(path.join(__dirname, '../build', cssPath), `/x-site-admin/${envCode}/public/build/` + cssPath);
                }
            }
            if (envCode === 'gray' || envCode === 'prod') {
                console.log('清空build目录');
                fse.emptyDirSync(path.join(__dirname, '../build'));
            }
        })()
    }
};


let OssMap = {
    'gray': "//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/gray/public/build/",
    'prod': "//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/prod/public/build/",
    'test': "/build/",
    'dev': "/build/"
}


/**
 *
 * @param assetItem
 * @return {{jsPath: *, cssPath: *}}
 * @private
 */
function _extraJsCssPath(assetItem) {
    if (Array.isArray(assetItem)) {
        return {
            jsPath: assetItem[0],
            cssPath: assetItem[1]
        }
    } else {
        console.log('assetItem::', assetItem);
        // throw new Error('这种情况应该只是生成JS的情况;;');
        return {
            jsPath: assetItem,
            cssPath: ""
        }
    }
}